package com.gitee.target123.develop.common.util;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.function.Predicate;

public class CommonUtil {

    /**
     * 拼接string
     * @param list 集合
     * @param split 分隔符
     * @param key 元素取值方法
     */
    public static <T> String listToString(List<T> list, String split, Function<? super T, ?> key){
        StringBuilder b = new StringBuilder();
        for (T t : list) {
            Object value = key.apply(t);
            if (value != null){
                if (b.length() > 0){
                    b.append(split);
                }
                b.append(value);
            }
        }
        return b.toString();
    }

    /**
     * 获取ip
     * @param request request
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * Stream去重方法
     * 例:
     * <code>
     *     Stream.filter(distinctByKey(Function.identity()));
     * </code>
     * @param key
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> key) {
        Set<Object> set = new TreeSet<>();
        return t -> set.add(key.apply(t));
    }

    /**
     * URLEncode
     * @param param
     * @return
     */
    public static String urlEncode(String param){
        try {
            return URLEncoder.encode(param,StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            return param;
        }
    }

    /**
     * URLDecode
     * @param param
     * @return
     */
    public static String urlDecode(String param){
        try {
            return URLDecoder.decode(param,StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            return param;
        }
    }
}
